import { getLogin, getInfoAPI, getLoginoutAPI } from "@/api/user";
import router from "@/router";
import { deepTree } from "@/utils/deepMenu";
export default {
  namespaced: true,
  state: {
    isAdd: false, //判断是否动态添加过路由
    token: sessionStorage.getItem("token") || "", //用户的token
    refreshToken: sessionStorage.getItem("refreshToken") || "", //用户刷新token的token
    info: JSON.parse(sessionStorage.getItem("info")) || {}, //用户信息
    menu: JSON.parse(sessionStorage.getItem("menu")) || [], //用户权限信息
    flag: JSON.parse(localStorage.getItem("false")) || false, //是否记住密码
  },
  mutations: {
    setIsAdd(state, payload) {
      state.isAdd = payload;
    },
    setToken(state, payload) {
      state.token = payload;
      sessionStorage.setItem("token", payload);
    },
    setRefreshToken(state, payload) {
      state.refreshToken = payload;
      sessionStorage.setItem("refreshToken", payload);
    },
    setInfo(state, payload) {
      state.info = payload;
      sessionStorage.setItem("info", JSON.stringify(payload));
    },
    setMenu(state, payload) {
      state.menu = payload;
      sessionStorage.setItem("menu", JSON.stringify(payload));
    },
    setFlag(state, payload) {
      localStorage.setItem("flag", JSON.stringify(payload));
      state.flag = payload;
    },
  },
  actions: {
    //登录
    async login(context, payload) {
      try {
        const result = await getLogin(payload);
        //将token刷新token写入token和刷新token
        context.commit("setToken", result.token);
        context.commit("setRefreshToken", result.refreshToken);
        return "ok";
      } catch (e) {
        return "error";
      }
    },
    //记住密码
    changFlag(context, payload) {
      context.commit("setFlag", payload);
    },
    //获取用户信息
    async getInfo({ commit }) {
      const { info, menus } = await getInfoAPI();
      commit("setInfo", info);
      commit("setMenu", deepTree(menus.filter((item) => item.type !== 2)));
      // 返回一级菜单动态添加到路由中(返回的结果会被路由前置守卫调用的getInfo返回)
      return menus.filter((item) => item.type === 1);
    },
    //用户登出（修改绑定的isAdd）
    async loginout({ commit }, flag = true) {
      //调用接口
      flag && (await getLoginoutAPI());
      commit("setIsAdd", false);
      //动态移除
      router.getRoutes().forEach((route) => {
        if (!route.meta.isKeep) {
          router.removeRoute(route.name);
        }
      });
      sessionStorage.clear();
      router.replace("/login");
    },
  },
};
